﻿/*
 *author:keily ,department 2,wuda geo
 *create date:2013-1-29
 *description:http操作类
 */

using System;
using System.Text;
using System.Net;
using System.IO;

namespace GeoWeb.Common
{
    /// <summary>
    /// Http操作类
    /// </summary>
    public class HttpHelper
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="uri">web request的url</param>
        public HttpHelper(Uri uri)
        {
            if (uri == null)
                throw new ArgumentNullException("uri");

            _webRequest = WebRequest.Create(uri);
        }

        private WebRequest _webRequest;
        /// <summary>
        /// 设置WebRequest的附加属性
        /// </summary>
        public WebRequest WebRequest
        {
            get { return _webRequest; }
        }

        /// <summary>
        /// 初始化get request
        /// </summary>
        /// <returns>返回html流的字符串</returns>
        public string Get()
        {
            //get
            _webRequest.Method = "GET";

            return SendWebRequest(this._webRequest);
        }

        /// <summary>
        /// 初始化一个post request
        /// </summary>
        /// <param name="postData">post到服务器的数据，调用前确认post的是经过html编码的.</param>
        /// <returns>返回html流的字符串</returns>
        public string Post(string postData)
        {
            _webRequest.Method = "POST";
            _webRequest.ContentType = "application/x-www-form-urlencoded";

            ASCIIEncoding encoder = new ASCIIEncoding();
            byte[] byteArray = encoder.GetBytes(postData);

            _webRequest.ContentLength = byteArray.Length;
            using (Stream postStream = _webRequest.GetRequestStream())
            {
                postStream.Write(byteArray, 0, byteArray.Length);
            }

            return SendWebRequest(this._webRequest);
        }

        /// <summary>
        ///  提供一个webrequest对象获取一个response流
        /// </summary>
        /// <param name="webRequest">一个包含请求的WebRequest对象</param>
        /// <returns>返回html流的字符串</returns>
        public string SendWebRequest(WebRequest webRequest)
        {
            if (webRequest == null)
                throw new ArgumentNullException("webRequest");

            using (HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse())
            {
                using (Stream dataStream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(dataStream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
        }
        /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="uri">文件url</param>
        /// <param name="destinationPath">下载存放目录</param>
        public void DownloadFile(Uri uri, string destinationPath)
        {
            DownloadFile(uri, null, destinationPath);
        }
        /// <summary>
        /// 下载文件。需要证书验证的https
        /// </summary>
        /// <param name="uri">文件url</param>
        /// <param name="credentials">证书</param>
        /// <param name="destinationPath">下载存放目录</param>
        public void DownloadFile(Uri uri, NetworkCredential credentials, string destinationPath)
        {
            HttpHelper wrapper = new HttpHelper(uri);
            if (credentials != null)
            {
                wrapper.WebRequest.Credentials = new NetworkCredential(credentials.UserName, credentials.Password);
            }
            using (HttpWebResponse response = (HttpWebResponse)wrapper.WebRequest.GetResponse())
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int num;
                        byte[] buffer = new byte[4194304];
                        while ((num = stream.Read(buffer, 0, buffer.Length)) != 0)
                        {
                            ms.Write(buffer, 0, num);
                        }
                        buffer = null;
                        if (!Directory.Exists(Path.GetDirectoryName(destinationPath)))
                        {
                            Directory.CreateDirectory(Path.GetDirectoryName(destinationPath));
                        }
                        using (FileStream fs = new FileStream(destinationPath, FileMode.Create, FileAccess.Write))
                        {
                            fs.Write(ms.ToArray(), 0, (int)ms.Length);
                            fs.Close();
                        }
                        ms.Close();
                    }
                    stream.Close();
                }
                response.Close();
            }
        }

    }

}
